<template>
<div class="preview-call-wrap">
  <continer :showPage="showPage" :shadow="true" :pageshadow="true" :isNoTabs="true">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="getIvrList"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="getIvrList">查询</el-button>
      <el-button @click="handleAdd" size="mini" v-functions="['preview_dialout_list_create']" >新建外呼任务</el-button>
    </template>
    <template slot="content">
      <configTable
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
        @checkHeadersChange="checkHeadersChange"
        v-loading="showLoading"
        :headersConfig="false"
        ref="configTabel"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
              v-if="
                item.prop !== 'oprate' &&
                item.prop !== 'status' &&
                item.prop !== 'createUser' &&
                item.prop !== 'progress' &&
                item.prop !== 'connectionRate'
              "
            >
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'createUser' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span :key="item.prop">{{ scope.row.createUser }}</span>
              </template>
            </u-table-column>
            <u-table-column
              width="80"
              :label="item.label"
              v-if="item.prop === 'status' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span :key="item.prop">{{ scope.row | getTaskStatus }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'progress' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <el-progress
                    style="width: 80px; margin-right: 8px"
                    :stroke-width="6"
                    :percentage="getProcess(scope.row)"
                    :show-text="false"
                  ></el-progress
                  ><span>{{ getFormat(scope.row) }}</span>
                </div>
              </template>
            </u-table-column>
            <u-table-column
              width="80"
              :label="item.label"
              v-if="item.prop === 'connectionRate' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                {{ getConnectionRate(scope.row) }}%
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'oprate' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
              fixed="right"
              :width="120"
            >
              <template slot-scope="scope">
                <span
                  v-show="
                    scope.row.status === 'READY' ||
                    scope.row.status === 'PAUSED'
                  "
                  class="oprate"
                  @click="changeState(scope.row, 'DEALING')"
                  v-functions="['preview_dialout_list_start_pause']"
                  >开启</span
                >
                <span
                  v-show="scope.row.status === 'DEALING'"
                  class="oprate"
                  v-functions="['preview_dialout_list_start_pause']"
                  @click="changeState(scope.row, 'PAUSED')"
                  >暂停</span
                >
                <span
                  class="oprate"
                  @click="handleEdit(scope.row)"
                  v-show="scope.row.status !== 'ARCHIVED'"
                  v-functions="['preview_dialout_list_edit']"
                  >编辑</span
                >
                <span
                  class="oprate"
                  @click="checkdDtails(scope.row)"
                  v-functions="['preview_dialout_list_view']"
                  >查看</span
                >
                <span
                  class="oprate delete"
                  @click="handleDeleteById(scope.row)"
                  v-functions="['preview_dialout_list_delete']"
                  v-show="
                    scope.row.status === 'READY' ||
                    scope.row.status === 'PAUSED' ||
                    scope.row.status === 'CLOSE'
                  "
                  >删除</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
    </template>
    <template slot="page">
      <priviewDetails
        @back="pageBack"
        @edit="detailsToEdit"
        @screen="detailsToSpringScreen"
        v-if="isShowPage('details')"
        :data="detailsData"
      ></priviewDetails>
      <springScreen
        @back="pageBack"
        @edit="detailsToEdit"
        v-show="isShowPage('springScreen')"
        :data="detailsData"
      ></springScreen>
    </template>
  </continer>
  <editOrAdd :drawerData="drawer" ref="editOrAddRef" @updateInfoSuccess="updateInfoSuccess"></editOrAdd>
</div>
</template>

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { CommonModule } from '@/store/modules/common/index'
import { IvrModule } from '@/store/modules/config/ivr'
import { ElMessageBoxShortcutMethod } from 'element-ui/types/message-box'
import { IvrData, PagingData, TabelHeaders } from './types/index'

import editOrAdd from './previewEditorAdd/index.vue'
import priviewDetails from './previewDetails/index.vue'
import springScreen from './springScreen/index.vue'

import taskMixin from './common/task-mixin'
interface DrawerObj {
  type: string
}
@Component({
  name: 'ServiceNumber',
  components: { continer, configTable, QuickSearch, editOrAdd, priviewDetails, springScreen }
})
export default class extends Mixins(taskMixin) {
  private $confirm: ElMessageBoxShortcutMethod | undefined
  private showLoading: boolean = false
  private drawer: DrawerObj = { type: 'add' }

  private detailsData: any = {}

  private currentPage = 'editOrAdd'

  private isShowPage (page: string) {
    return this.currentPage === page
  }

  private mounted (): void {
    this.getIvrList()
  }

  // 详情控制
  private showPage: boolean = false

  private pagingData: PagingData = { total: 0, limit: 10, page: 1 }

  private tableHeaders: TabelHeaders[] = [
    {
      label: '任务名称',
      prop: 'name'
    },
    {
      label: '任务状态',
      prop: 'status'
    },
    {
      label: '创建时间',
      prop: 'createTime',
      sortable: true
    },
    {
      label: '创建人',
      prop: 'createUserName'
    },
    {
      label: '修改时间',
      prop: 'updateTime',
      sortable: true
    },
    {
      label: '修改人',
      prop: 'updateUserName'
    },
    {
      label: '任务进度',
      prop: 'progress'
    },
    {
      label: '接通率',
      prop: 'connectionRate'
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  private checkHeaders: TabelHeaders[] = []
  private tableData: IvrData[] = []

  private stateOptions = [{
    name: '全部',
    _id: ''
  }, {
    name: '未开启',
    _id: 'READY'
  }, {
    name: '执行中',
    _id: 'DEALING'
  }, {
    name: '已暂停',
    _id: 'PAUSED'
  }, {
    name: '已完成',
    _id: 'CLOSE'
  }, {
    name: '已归档',
    _id: 'ARCHIVED'
  }]

  private quickSearchForm = { // 快捷检索数据（时间条件，类型）
    form: {
      name: '',
      status: ''
    },
    advSearchOptions: [ // 快捷检索的数据(语音文件名称)
      { label: '任务名称', inputType: 'input', placeholder: '请输入任务名称', name: 'name', clearable: true },
      { label: '外呼任务状态', inputType: 'select', clearable: true, selectData: this.stateOptions, name: 'status' }
    ]
  }

  private pageChange (page: number): void {
    this.pagingData.page = page
    this.getIvrList()
  }

  private handleDeleteById (row: any) {
    (this.$confirm as any)('确定删除该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const taskId = row._id
      this.handleDelete(taskId).then((success) => {
        if (success) {
          this.getIvrList()
        }
      })
    }).catch(e => {
      console.log(e)
    })
  }

  private pageSizeChange (size: number): void {
    this.pagingData.page = 1
    this.pagingData.limit = size
    this.getIvrList()
  }

  private changeState (row: any, status: string) {
    const taskId = row._id
    const oldStatus = row.status
    row.status = status
    this.updateTaskState(taskId, status).then((success) => {
      if (!success) {
        row.status = oldStatus
      }
    })
  }

  private handleEdit (row): void {
    this.$nextTick(() => {
      (this as any).$refs.editOrAddRef.openOrCloseDrawer(row)
      this.drawer = { type: 'edit' }
    })
  }

  private detailsToEdit () {
    if (this.detailsData) {
      this.$nextTick(() => {
        (this as any).$refs.editOrAddRef.openOrCloseDrawer(this.detailsData)
        this.drawer = { type: 'edit' }
      })
    }
  }

  private detailsToSpringScreen () {
    this.currentPage = 'springScreen'
  }

  private checkdDtails (row: any) {
    this.currentPage = 'details'
    this.detailsData = row
    this.showPage = true
  }

  private checkHeadersChange (checkList): void {
    this.$set(this, 'checkHeaders', checkList)
  }

  private pageBack (isRefresh): void {
    if (isRefresh) {
      this.getIvrList()
    }
    this.showPage = false
  }

  private handleAdd (): void {
    this.$nextTick(() => {
      (this as any).$refs.editOrAddRef.openOrCloseDrawer({})
      this.drawer = { type: 'add' }
    })
  }

  private updateInfoSuccess (data: any) {
    Object.keys(data).forEach((key) => {
      this.detailsData[key] = data[key]
    })
    this.getIvrList()
  }

  private getIvrList (): void {
    this.showLoading = true
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page, module: 'MASTER', account: this.account }, this.quickSearchForm.form)
    const data = { url: '/call/action/task/list', method: 'POST', hideLoading: true, data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.data) {
        const resList = res.data.list || []
        if (resList.length === 0) {
          const page = Math.ceil(res.data.count / this.pagingData.limit)
          if (!res.data.count) { // 第一页且count为0是不再发请求（!res.data.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.getIvrList()
            return false
          }
        }
        for (let i = 0; i < resList.length; i++) {
          const element = resList[i]
          element.updateUserName = this.userList[element.updateUser]?.agentName
        }
        this.tableData = resList
        this.pagingData.total = res.data.count || 0
      }
      this.showLoading = false
    }).catch(() => {
      this.tableData = []
      this.pagingData.total = 0
      this.showLoading = false
    })
  }

  public get userList (): any {
    return CommonModule.publicCache.userListObj
  }
}
</script>

<style lang="stylus" scoped>
.page
  box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
.status
  font-size 14px
  color $c-danger
.enable
  color $c-green
.oprate
  color $c-main
  margin-right 10px
  cursor pointer
.isEnable
  color $c-danger
.oprate:hover
  opacity 0.8
.delete
  color $c-danger
.preview-call-wrap
  width 100%
  height 100%
</style>
